package org.example.app.web.api.Impl;


import com.alibaba.fastjson.JSON;
import io.micrometer.common.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.example.app.model.User;
import org.example.app.repository.UserRepository;
import org.example.app.service.BookKeepService;
import org.example.app.service.UserService;
import org.example.app.service.dto.ReturnDto;
import org.example.app.service.dto.UserDto;
import org.example.app.service.util.JwtUtil;
import org.example.app.service.util.MD5Util;
import org.example.app.web.api.userController;
import org.example.app.web.vm.UserVm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class userControllerImpl implements userController {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private BookKeepService bookKeepService;
    /**
     * 用户登录
     * */
    @Operation(summary = "用户登录")
    @PostMapping("/user/login")
    @Override
    public String login(@RequestBody UserVm userVm){
//        System.out.println("正在调用_用户登录接口_");

        if(StringUtils.isBlank(userVm.getUsername()) || StringUtils.isBlank(userVm.getPassword())){
            return JSON.toJSONString(new ReturnDto(-1,"用户名或密码必传",null));
        }
        // 获取用户的信息，用变量存储
        String username = userVm.getUsername();
        String password = userVm.getPassword();

        // 身份验证
        User user = userRepository.findFirstByUsername(username);
        if(user == null) {
            return JSON.toJSONString(new ReturnDto(-1,"用户不存在",null));
        }
        if(!Objects.equals(MD5Util.getMD5(password), user.getPassword())) {
            return JSON.toJSONString(new ReturnDto(-1,"密码错误",null));
        }
        String token = JwtUtil.generateToken(user.getId().toString());
        //修改后的登录接口，方便前端登录后得到用户id，加载用户信息
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("userId", user.getId());

//        System.out.println("用户登录成功");

        return JSON.toJSONString(new ReturnDto(1, "登录成功", data));

        //return JSON.toJSONString(new ReturnDto(1,"登录成功",token));

    }


    /**
     * 用户注册
     * */
    @Operation(summary = "用户注册")
    @PostMapping("/user")
    @Override
    public String register(@RequestBody UserVm userVm){
        if(StringUtils.isBlank(userVm.getUsername())){
            return JSON.toJSONString(new ReturnDto(-1,"用户名必须传",null));
        }
        if(StringUtils.isBlank(userVm.getPassword())){
            return JSON.toJSONString(new ReturnDto(-1,"密码必须传",null));
        }
        if(StringUtils.isBlank(userVm.getRealname())){
            return JSON.toJSONString(new ReturnDto(-1,"真实姓名必须传",null));
        }
        if(! userVm.getPassword().equals(userVm.getNewPassword())){
            return JSON.toJSONString(new ReturnDto(-1,"新密码与旧密码不相同",null));
        }
        if(StringUtils.isBlank(userVm.getEmail())){
            return JSON.toJSONString(new ReturnDto(-1,"邮箱必须传",null));
        }
       User user = userRepository.findByUsername(userVm.getUsername());
        if(user != null){
            return JSON.toJSONString(new ReturnDto(-1,"用户已存在",null));
        }
        // 在服务层处理事务
        userService.create(userVm);

        return JSON.toJSONString(new ReturnDto(1,"创建成功",null));
    }
    /**
     *   获取用户列表
     * */
    @GetMapping("/users")
    @Operation(summary = "获取用户列表")
    public String getList(HttpServletRequest request){

        //获取token
        String token = JwtUtil.getJwtFromRequest(request);
        //检查token是否传过来
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1,"非法请求",null));
        }
        //检查token是否传正确，是否是系统生成的令牌
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9,"token过期",null));
        }

        List<User> userList = userRepository.findAll();
        //是将user的list变为userDto的list
        //stream
        List<UserDto> userDtos = userList.stream().map(UserDto::new).collect(Collectors.toList());
//        System.out.println("获取成功");

        return JSON.toJSONString(new ReturnDto(1,"查询成功",userDtos));
    }


    /**
     * 获取用户详情
     * */
    @GetMapping("/user/{id}")
    @Operation(summary = "获取用户详情")
    @Override
    public String getDetail(@PathVariable Integer id, HttpServletRequest request){
//        System.out.println("正在调用_获取用户详情接口_");
        //获取token
        String token = JwtUtil.getJwtFromRequest(request);
        //检查token是否传过来
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1,"非法请求",null));
        }
        //检查token是否传正确，是否是系统生成的令牌
        String userId;
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            //
            return JSON.toJSONString(new ReturnDto(-9,"token过期",null));
        }

        Optional<User> user = userRepository.findById(id);
        if (!user.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1,"参数有误",null));
        }
//        System.out.println(new UserDto(user.get()));
//        System.out.println("获取成功");
        return JSON.toJSONString(new ReturnDto(1,"查询成功",new UserDto(user.get())));
    }

    /**
     * 修改用户信息
     * @PathVariable 用于获取路径的 id值
     * */
    @PutMapping("/user/{id}")
    @Operation(summary = "修改用户信息")
    @Override
    public String update(@PathVariable Integer id,@RequestBody UserVm userVm,HttpServletRequest request){
        // 解析http请求
        String token = JwtUtil.getJwtFromRequest(request);
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1,"非法请求",null));
        }
        //检查token是否传正确，是否是系统生成的令牌
        String userId = "";
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9,"token过期",null));
        }
        if (Integer.parseInt(userId) != id){
            return JSON.toJSONString(new ReturnDto(-1,"非法编辑",null));
        }
        //先查询数据库中，是否有该数据
        Optional<User> user = userRepository.findById(id);
        if(!user.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1,"参数有误",null));
        }
        if (StringUtils.isBlank(userVm.getRealname())){
            return JSON.toJSONString(new ReturnDto(-1,"真实姓名必传",null));
        }
        User updateUser = userService.update(userVm, user.get());
        return JSON.toJSONString(new ReturnDto(1,"修改成功",new UserDto(updateUser)));
    }

    /**
     * 删除用户
     * */
    @DeleteMapping("/user/{id}")
    @Operation(summary = "删除用户")
    @Override
    public String delete(@PathVariable Integer id, HttpServletRequest request){
        // 解析http请求
        String token = JwtUtil.getJwtFromRequest(request);
        if(StringUtils.isBlank(token)){
            return JSON.toJSONString(new ReturnDto(-1,"非法请求",null));
        }
        //检查token是否传正确，是否是系统生成的令牌
        String userId = "";
        try {
            userId = JwtUtil.parseToken(token);
        }catch (Exception e){
            return JSON.toJSONString(new ReturnDto(-9,"token过期",null));
        }
        if (Integer.parseInt(userId) != id){
            return JSON.toJSONString(new ReturnDto(-1,"非法删除",null));
        }
        Optional<User> userOpt = userRepository.findById(id);
        if (!userOpt.isPresent()){
            return JSON.toJSONString(new ReturnDto(-1,"参数有误",null));
        }
        User user = userOpt.get();
        userService.delete(user);


        return JSON.toJSONString(new ReturnDto(1,"删除成功",null));
    }
    @Operation(summary = "重置密码")
    @Override
    @PostMapping("/user/resetPassword")
    public String resetPassword(@RequestBody UserVm userVm) {
        User user = userRepository.findByUsername(userVm.getUsername());
        if (user == null){
            return JSON.toJSONString(new ReturnDto(-1,"用户不存在",null));
        }
        userService.resetPassword(userVm,user);
        return JSON.toJSONString(new ReturnDto(1,"重置密码成功",null));
    }
    @Operation(summary = "发送邮件")
    @PostMapping("/emailCode")
    @Override
    public String emailCode(@RequestBody UserVm userVm) {
        User user = userRepository.findByUsername(userVm.getUsername());
        if (user == null){
            return JSON.toJSONString(new ReturnDto(-1,"用户不存在",null));
        }
        String code = userService.emailCode(user);
        return JSON.toJSONString(new ReturnDto(1,"发送成功",code));
    }


}
